const inputs = document.querySelectorAll(".input")

function addcl() {
    let parent = this.parentNode.parentNode;
    parent.classList.add("focus")
}

function remcl() {
    let parent = this.parentNode.parentNode;
    if (this.value === "") {
        parent.classList.remove("focus")
    }
}

inputs.forEach(input => {
    input.addEventListener("focus", addcl);
    input.addEventListener("blur", remcl);
})

// dom操作
// 选择元素
var layer = $('.layer');
var layer_info = $('.layer div div');

// 失败
// layer_info.attr('id','error');
// layer_info.append('<i class="fas fa-tired"><span> 登录失败</span></i>');
// 成功
// layer_info.attr('id', 'success');
// layer_info.append('<i class="fas fa-smile"><span> 登录成功</span></i>');
// // 淡入 淡出
// layer.fadeIn(600);
// setTimeout(function () { layer.fadeOut(450); }, 1500);

// 登录
$('.btn').click(function () {
    var info = $('form input');
    $.ajax({
        type: 'POST',
        url: './api/users/login',
        data: {
                "username": info[0].value,
                "password": info[1].value
        },
        dataType: "json",
        success: function (data) {
            console.log(data);
            if(data.status == "error"){
                layer_info.attr('id', 'error');
                layer_info.append(`<i class="fas fa-tired"><span> 登录失败：${data.data}</span></i>`);
                layer.fadeIn(600);
                setTimeout(function () { layer.fadeOut(450); }, 1500);
                // 清楚layer_info的id和内容
                setTimeout(() => { layer_info.removeAttr('id'); layer_info.empty(); }, 3000);
                return null;
            }
            console.log(data);
            layer_info.attr('id', 'success');
            layer_info.append('<i class="fas fa-smile"><span> 登录成功</span></i>');
            layer.fadeIn(600);
            setTimeout(function () { layer.fadeOut(450); }, 1500);
            // 保存username
            localStorage.setItem("username", data.data)
            setTimeout(function () { window.location.href = '/'; }, 1500);
        },
        error: function (err) {
            console.log(err.responseText);
            // 失败
            layer_info.attr('id', 'error');
            errorMessage = err.responseText.match(/[\u4e00-\u9fa5]+/g);
            layer_info.append(`<i class="fas fa-tired"><span> 登录失败: ${errorMessage}</span></i>`);
            layer.fadeIn(600);
            setTimeout(function () { layer.fadeOut(450); }, 1500);
            // 清楚layer_info的id和内容
            setTimeout(() => { layer_info.removeAttr('id'); layer_info.empty(); }, 3000);
        }
    });
    $('input').val('');
});